package logic

import (
	"context"
	"errors"
	"nate_srv/models"

	"nate_srv/internal/svc"
	"nate_srv/nate"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *nate.LoginRequest) (*nate.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	u.Account = in.Account
	if err = u.GetUserByAccount(); err != nil {
		logx.Error("获取用户信息失败")
		return nil, errors.New("获取用户信息失败")
	}

	if u.ID == 0 {
		u.Account = in.Account
		u.Password = in.Password
		if err = u.Register(); err != nil {
			logx.Error("用户注册失败")
			return nil, errors.New("用户注册失败")
		}
	}

	if u.Password != in.Password {
		logx.Error("密码错误")
		return nil, errors.New("密码错误")
	}

	return &nate.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
